import Mock from 'mockjs';

// 创建内存数据库
const mockDatabase = (() => {
  // 生成用户数据
  const generateUsers = () => {
    return Mock.mock({
      'list|30-50': [
        {
          'id|+1': 1,
          'username': '@word(5, 10)',
          'name': '@cname',
          'email': '@email',
          'phone': /1[3-9]\d{9}/,
          'role': '@pick(["admin", "lawyer", "user"])',
          'avatar': '@image("100x100", "#4A7BF7", "Avatar")',
          'status|0-1': 0, // 0-正常, 1-禁用
          'gender|0-1': 0, // 0-男, 1-女
          'age|18-65': 25,
          'address': '@county(true)',
          'idCard': /[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]/,
          'education': '@pick(["高中", "大专", "本科", "硕士", "博士"])',
          'occupation': '@pick(["学生", "教师", "医生", "工程师", "销售", "其他"])',
          'income': '@pick(["3000以下", "3000-5000", "5000-8000", "8000-12000", "12000以上"])',
          'createdAt': '@datetime',
          'lastLoginAt': '@datetime',
          'caseCount|0-10': 0,
          'lawyerId': null
        }
      ]
    }).list;
  };

  return {
    users: generateUsers()
  };
})();

/**
 * 用户模块Mock配置
 * @param {MockAdapter} mock - Mock适配器实例
 */
export default function(mock) {
  // 获取用户列表（带分页）
  mock.onGet('/users').reply(config => {
    const { page = 1, size = 10, role, status, keyword } = config.params;
    
    let filteredUsers = [...mockDatabase.users];
    
    // 角色筛选
    if (role) {
      filteredUsers = filteredUsers.filter(u => u.role === role);
    }
    
    // 状态筛选
    if (status !== undefined) {
      filteredUsers = filteredUsers.filter(u => u.status === parseInt(status));
    }
    
    // 关键词搜索
    if (keyword) {
      filteredUsers = filteredUsers.filter(u => 
        u.name.includes(keyword) || 
        u.username.includes(keyword) || 
        u.email.includes(keyword) ||
        u.phone.includes(keyword)
      );
    }
    
    const start = (page - 1) * size;
    const end = start + size;
    const paginated = filteredUsers.slice(start, end);
    
    return [200, {
      code: 200,
      data: paginated,
      pagination: {
        page: parseInt(page),
        size: parseInt(size),
        total: filteredUsers.length,
        totalPages: Math.ceil(filteredUsers.length / size)
      }
    }];
  });

  // 获取单个用户
  mock.onGet(/\/users\/\d+$/).reply(config => {
    const userId = config.url.split('/').pop();
    const user = mockDatabase.users.find(u => u.id == userId);
    
    return user 
      ? [200, { code: 200, data: user }]
      : [404, { code: 404, message: '用户不存在' }];
  });

  // 创建用户
  mock.onPost('/users').reply(config => {
    const newUser = JSON.parse(config.data);
    newUser.id = Math.max(...mockDatabase.users.map(u => u.id)) + 1;
    newUser.createdAt = new Date().toISOString();
    newUser.status = 0; // 新用户默认正常状态
    newUser.avatar = Mock.Random.image('100x100', '#4A7BF7', 'Avatar');
    newUser.caseCount = 0;
    
    mockDatabase.users.unshift(newUser);
    
    return [201, { 
      code: 201, 
      message: '用户创建成功',
      data: newUser
    }];
  });

  // 更新用户
  mock.onPut(/\/users\/\d+$/).reply(config => {
    const userId = config.url.split('/').pop();
    const updateData = JSON.parse(config.data);
    
    const userIndex = mockDatabase.users.findIndex(u => u.id == userId);
    
    if (userIndex === -1) {
      return [404, { code: 404, message: '用户不存在' }];
    }
    
    // 更新用户信息
    mockDatabase.users[userIndex] = {
      ...mockDatabase.users[userIndex],
      ...updateData,
      id: parseInt(userId) // 确保ID不被修改
    };
    
    return [200, { 
      code: 200, 
      message: '用户信息更新成功',
      data: mockDatabase.users[userIndex]
    }];
  });

  // 删除用户
  mock.onDelete(/\/users\/\d+$/).reply(config => {
    const userId = config.url.split('/').pop();
    const userIndex = mockDatabase.users.findIndex(u => u.id == userId);
    
    if (userIndex === -1) {
      return [404, { code: 404, message: '用户不存在' }];
    }
    
    mockDatabase.users.splice(userIndex, 1);
    
    return [200, { 
      code: 200, 
      message: '用户删除成功' 
    }];
  });

  // 批量删除用户
  mock.onPost('/users/batch-delete').reply(config => {
    const { ids } = JSON.parse(config.data);
    
    if (!Array.isArray(ids) || ids.length === 0) {
      return [400, { code: 400, message: '请选择要删除的用户' }];
    }
    
    const deletedCount = ids.length;
    mockDatabase.users = mockDatabase.users.filter(u => !ids.includes(u.id));
    
    return [200, { 
      code: 200, 
      message: `成功删除 ${deletedCount} 个用户` 
    }];
  });

  // 更新用户状态
  mock.onPatch(/\/users\/\d+\/status/).reply(config => {
    const userId = config.url.split('/').pop();
    const { status } = JSON.parse(config.data);
    
    const user = mockDatabase.users.find(u => u.id == userId);
    
    if (!user) {
      return [404, { code: 404, message: '用户不存在' }];
    }
    
    user.status = status;
    
    return [200, { 
      code: 200, 
      message: '用户状态更新成功',
      data: user
    }];
  });

  // 获取用户统计信息
  mock.onGet('/users/stats').reply(() => {
    const totalUsers = mockDatabase.users.length;
    const activeUsers = mockDatabase.users.filter(u => u.status === 0).length;
    const disabledUsers = mockDatabase.users.filter(u => u.status === 1).length;
    
    const roleStats = {
      admin: mockDatabase.users.filter(u => u.role === 'admin').length,
      lawyer: mockDatabase.users.filter(u => u.role === 'lawyer').length,
      user: mockDatabase.users.filter(u => u.role === 'user').length
    };
    
    const genderStats = {
      male: mockDatabase.users.filter(u => u.gender === 0).length,
      female: mockDatabase.users.filter(u => u.gender === 1).length
    };
    
    return [200, {
      code: 200,
      data: {
        total: totalUsers,
        active: activeUsers,
        disabled: disabledUsers,
        roleStats,
        genderStats,
        recentUsers: mockDatabase.users
          .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
          .slice(0, 5)
      }
    }];
  });

  // 用户头像上传
  mock.onPost('/users/avatar').reply(config => {
    // 模拟文件上传
    const avatarUrl = Mock.Random.image('200x200', '#4A7BF7', 'Avatar');
    
    return [200, {
      code: 200,
      message: '头像上传成功',
      data: {
        avatarUrl
      }
    }];
  });

  // 用户个人信息更新
  mock.onPut('/users/profile').reply(config => {
    const updateData = JSON.parse(config.data);
    
    // 这里应该根据当前登录用户更新信息
    // 简化处理，返回成功
    return [200, {
      code: 200,
      message: '个人信息更新成功',
      data: updateData
    }];
  });
} 